package com.sunrise.xdoc.security;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Query;

import com.sunrise.xdoc.helper.DaoHelper;

/**
 * Store the map functionCode -> functionMode of a user. This bean is initialized and stored in session scope. When the
 * user login, this class must be called 1 time.
 */
public class SecurityCached {
    private DaoHelper daoHelper;

    private Map<String, Set<FunctionMode>> accessibleFuntions = new HashMap<>();

    /**
     * TODO: This method is called from login + There is 1 link on screen to do this job
     */
    public void refreshSecurity() {
        // load security from database. TODO: test code, should have real refreshing
        // accessibleFuntions.clear();
        if (accessibleFuntions.isEmpty()) {
            String defaulUser = "php"; // TODO: This must be retrieve from contextProvider
            String queryString = "SELECT f.code, pri.possible_mode "
                    + "FROM op_function f JOIN op_privilege pri ON f.id=pri.function_id "
                    + "JOIN op_operator_profile prof ON prof.id = pri.profile_id "
                    + "JOIN op_operator_role role ON role.profile_id = prof.id "
                    + "JOIN op_operator op ON op.id = role.operator_id "
                    + "JOIN security_user usr ON op.user_id = usr.id "
                    + "WHERE username = 'php' AND (role.start_date IS NULL OR role.start_date < CURDATE()) "
                    + "AND (role.end_date IS NULL OR role.end_date > CURDATE()) ";
            Query query = getDaoHelper().getSession().createSQLQuery(queryString);
            List result = query.list();
            for (Object arr : result) {
                Object[] row = (Object[]) arr;
                String functionCode = row[0].toString();
                String possibleMode = row[1].toString();

                mergeToAccessibleFuntion(functionCode, possibleMode);
            }
        }

    }

    private void mergeToAccessibleFuntion(String functionCode, String possibleMode) {
        Set<FunctionMode> currentModes = accessibleFuntions.get(functionCode);
        if (currentModes == null) {
            currentModes = new HashSet<>();
        }
        currentModes.addAll(FunctionMode.toFuntionMode(possibleMode));
        accessibleFuntions.put(functionCode, currentModes);
    }

    public Set<FunctionMode> getAccessibleMode(String functionCode) {
        return accessibleFuntions.get(functionCode);
    }

    public DaoHelper getDaoHelper() {
        return daoHelper;
    }

    public void setDaoHelper(DaoHelper daoHelper) {
        this.daoHelper = daoHelper;
    }
}
